var LOC_EPTABLE = 0;
var LOC_MAINLINK = 1;
var CURRENT_LOCATION = 0;

var ROW_SIZE = 2;
var PAGE_SIZE = 8;

var htmlRowIndex = 0;
var pageIndex = 0;

//ep table listener
addListener(menuBar = function(actionKey, currentLocation){
	if(currentLocation == LOC_EPTABLE){
		switch(actionKey){
			case ACTION_KEYDOWN_LEFT:
			keyDown_direction_epTable(epTableIndex, epTableIndex-getIndexIncrement());
			break;
			case ACTION_KEYDOWN_RIGHT:
			keyDown_direction_epTable(epTableIndex, epTableIndex+getIndexIncrement());
			break;
			case ACTION_KEYDOWN_UP:
			keyDown_direction_epTable(epTableIndex, epTableIndex-(getIndexIncrement()*ROW_SIZE));
			break;
			case ACTION_KEYDOWN_DOWN:
			keyDown_direction_epTable(epTableIndex, epTableIndex+(getIndexIncrement()*ROW_SIZE));
			break;
			case ACTION_KEYUP_ENTER:
			keyEnterEpTable();
			break;
			case ACTION_KEYDOWN_DOUBLEKEY:
			keyDoubleEpTableNavBar();
			break;
		}
	}
});

//main link listener
addListener(menuBar = function(actionKey, currentLocation){
	if(currentLocation == LOC_MAINLINK){
		switch(actionKey){
			case ACTION_KEYDOWN_DOUBLEKEY:
			keyUp_DownMainLink();
			break;
			case ACTION_KEYUP_ENTER:
			keyUp_EnterMainLink();
			break;
		}
	}
});

function keyUp_DownMainLink(){
	CURRENT_LOCATION = LOC_NAVBAR;
	
	$('homeIcon').removeClassName('homeIconSelected');
	$('homeIcon').addClassName('homeIcon');
}

function keyUp_EnterMainLink(){
	location.href = 'index.php';
}

function keyDoubleEpTableNavBar(){
	CURRENT_LOCATION = LOC_MAINLINK;
	
	$('homeIcon').removeClassName('homeIcon');
	$('homeIcon').addClassName('homeIconSelected');
}

function keyDown_direction_epTable(fromIndex, toIndex){
	if(toIndex < 0){
		toIndex = numEps-1;
	
	}else if(toIndex >= numEps){
		toIndex = 0;
	}
	
	epTableIndex = toIndex;
	var oldPageIndex = pageIndex;
	
	setPageIndex();
	
	if(oldPageIndex != pageIndex){
		scrollEpList(oldPageIndex, pageIndex);
	}	
		
	updateScrollbar(fromIndex, epTableIndex);
	unselectEp(fromIndex);
	selectEp(epTableIndex);
}

function keyEnterEpTable(){
	var div = $('ep'+epTableIndex);
	location.href = div.readAttribute('link');
}

function setPageIndex(){
	pageIndex = ~~(epTableIndex / PAGE_SIZE);
}

function setRowIndex(){
	pageIndex = (epTableIndex % PAGE_SIZE);
}

function scrollEpList(fromPage, toPage){
	animating = true;
	var an = new Animator().addSubject(
	new NumericalStyleSubject(
		"screenshotTable",
		"margin-top",
		(((fromPage*4)*-1)*232.75),
		(((toPage*4)*-1)*232.75)));
	
	an.toggle();
}

function updateScrollbar(fromIndex, toIndex){
	var fromPercent = (fromIndex/(numEps-1))*100;
	var toPercent = (toIndex/(numEps-1))*100;
	var an = new Animator().addSubject(
	new NumericalStyleSubject(
		"scrollNub",
		"margin-top",
		(fromPercent*7.93),
		(toPercent*7.93)));
	an.toggle();
}
